package com.qdlc.p2p.biz.executer;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

import com.qdlc.p2p.biz.service.AccountService;
import com.qdlc.p2p.common.constant.LogTemplateType;
import com.qdlc.p2p.common.util.BeanUtil;
import com.qdlc.p2p.common.util.FreemarkerUtil;
import com.qdlc.p2p.common.util.LogFactory;
import com.qdlc.p2p.dal.common.LogTemplateHelper;
import com.qdlc.p2p.dal.dao.AccountDao;
import com.qdlc.p2p.dal.dao.AccountLogDao;
import com.qdlc.p2p.dal.dto.Account;
import com.qdlc.p2p.dal.dto.AccountLog;
import com.qdlc.p2p.dal.dto.User;
import com.qdlc.p2p.dal.util.SystemConfigs;

public abstract class AbstractAccountHandleExecutor extends AbstractBusinessExecutor implements AccountHandleExecutor {

	private static final Logger logger = LogFactory.EXCEPTION_LOGGER;
	
	protected AccountDao accountDao;
	
	protected AccountLogDao accountLogDao;

	protected AccountService accountService;
	
	protected AbstractAccountHandleExecutor(){
		perpare();
	}
	
	private void perpare(){
		accountDao = BeanUtil.getBean(AccountDao.class);
		accountLogDao = BeanUtil.getBean(AccountLogDao.class);
		accountService =  BeanUtil.getBean(AccountService.class);
	}
	
    public void addAccountLog(User user, double money, String accountLogType, Map<String, Object> templateDataMap) {
        Account account = accountDao.findByUserId(user.getUserId());
        AccountLog log = new AccountLog(user, accountLogType, new User(SystemConfigs.ADMIN_ID));
        log.setMoney(money);
        log.setTotal(account.getTotal());
        log.setUseMoney(account.getUseMoney());
        log.setNoUseMoney(account.getNoUseMoney()); 
        log.setCollection(account.getCollection());
        
        Map<String, Object> templateMap = new HashMap<String, Object>();
        if(templateDataMap != null&&templateDataMap.size()>0){
        	templateMap.putAll(templateDataMap);
        }
		templateMap.put("money", money);
		templateMap.put("user", user);
        String logRemark = getLogRemark(accountLogType, templateMap);
        log.setRemark(logRemark);
        
        accountLogDao.save(log);
    }
    
	protected String getLogRemark(String accountLogType, Map<String, Object> templateDataMap) {
		String template = LogTemplateHelper.getValue(LogTemplateType.ACCOUNT_LOG, accountLogType);
		try {
			return FreemarkerUtil.renderTemplate(template, templateDataMap);
		} catch (Exception e) {
			logger.error("根据模板生成备注信息失败", e);
		}
		return "";
	}
	
}
